<?php

namespace app\common\model;

use think\Model;

/**
 * 短信验证码
 */
class UserDayScore extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    // 追加属性
    protected $append = [
    ];


    public function getCreateTimeAttr($value)
    {
        return is_numeric($value) ? date('Y-m-d H:i:s', $value) : $value;
    }

    /**
     * 每日积分更新
     * @param $userId
     * @param $type
     * @param $score
     * @param int $record_type
     */
    public static function changeScore($userId, $type, $score, $record_type = 1)
    {
        $row_info = self::where('user_id', $userId)->where('type', $type)->find();
        if (!$row_info) {
            if ($record_type == 1) {
                $ddata = [
                    'user_id' => $userId,
                    'score' => $score,
                    'type' => $type,
                ];

                self::create($ddata);
            }
        } else {
            if ($record_type == 0) {
                if ($row_info->score < $score) {
                    $row_info->score = 0;
                } else {
                    $row_info->score -= $score;
                }
            } else {
                $row_info->score += $score;
            }

            $row_info->save();
        }
    }
}
